package org.sdau.rotten.library.config;

import org.sdau.rotten.library.entity.User;
import org.sdau.rotten.library.service.UserService;
import org.sdau.rotten.library.dao.UserDAO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component("authorizer")
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private UserDAO userDao;

    @Override
    protected AuthorizationInfo  doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        String userName = (String) getAvailablePrincipal(principals);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        System.out.println(info);
        //info.addStringPermission("user:add");

        User currentUser = userDao.selectById(userName);//拿到user对象

        System.out.println("权限"+currentUser.getAuthority()+userName);
        //设置当前用户的权限
        info.addStringPermission(currentUser.getAuthority());
        System.out.println(info.getStringPermissions());
        return info;

    }

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        String username = userToken.getUsername();
        String password = String.valueOf(userToken.getPassword());
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        User user = userService.isExist(username,password);
        System.out.println("----->>userInfo="+user);
        if(user == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                username, //用户名
                password, //密码
                "" //realm name
        );
        return authenticationInfo;
    }

}